package com.changgou.order.config;


import com.changgou.common.util.TokenDecode;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@EnableResourceServer
//激活所有处理器中方法上面使用的security相关注解；如：preAuthorize
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    /**
    * 配置token存储对象
    * 主要设置读取时使用公钥读取
    */
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter converter){
        return new JwtTokenStore(converter);
    }


    /**
    * 注册令牌转换器
    * 利用公钥读取解析令牌
    */
    @Bean
    public JwtAccessTokenConverter converter(){
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //设置校验令牌的公钥
        converter.setVerifierKey(TokenDecode.getPubKey());
        return converter;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //除了以下请求是不需要校验的，其它全部需要校验令牌
                //.antMatchers("/user/add", "/user/load/*").permitAll()
                .anyRequest().authenticated();
    }
}
